#include "EntityManager.h"

EntityManager * EntityManager::instance = NULL;

EntityManager * EntityManager::get()
{
	if (!instance) 
		instance = new EntityManager();
	return instance;
}

EntityManager::EntityManager(void)
{
}

EntityManager::~EntityManager(void)
{
}

Entity * EntityManager::createEntity(const char * fileName)
{
	Mesh * mesh = ModelLoader::get()->loadModel(fileName);
	if (mesh == NULL) 
		return NULL;

	bool success = false;
	GLuint glId = createGLIdForMesh(mesh, &success);

	if (success == true)
	{
		Entity * entity = new Entity(mesh, glId);
		entityList.push_back(entity);
		return entity;
	}
	return NULL;
}

GLuint EntityManager::createGLIdForMesh(Mesh * mesh, bool * success)
{
	Mesh::FaceIterator startIt = mesh->getFaceStartIter();
	Mesh::FaceIterator endIt = mesh->getFaceEndIter();

	if (startIt == endIt)
	{
		*success = false;
		return 0;
	}

	GLuint dlist;
	dlist = glGenLists(1);
	glNewList(dlist, GL_COMPILE);
	glEnable(GL_TEXTURE_2D);

	for (; startIt != endIt; ++startIt)
	{
		Triangle face = (*startIt);
		if (face.hasMaterial())
		{
			glBindTexture(GL_TEXTURE_2D, (*face.textureId));
		}
		glBegin(GL_TRIANGLES);

		TexCoord2D t1 = mesh->getTexCoordAt(face.tIndex[0]);
		glTexCoord2f(t1.u, t1.v);
		Vertex3D v1 = mesh->getVertexAt(face.vIndex[0]);
		glVertex3f(v1.x, v1.y, v1.z);
		TexCoord2D t2 = mesh->getTexCoordAt(face.tIndex[1]);
		glTexCoord2f(t2.u, t2.v);
		Vertex3D v2 = mesh->getVertexAt(face.vIndex[1]);
		glVertex3f(v2.x, v2.y, v2.z);
		TexCoord2D t3 = mesh->getTexCoordAt(face.tIndex[2]);
		glTexCoord2f(t3.u, t3.v);
		Vertex3D v3 = mesh->getVertexAt(face.vIndex[2]);
		glVertex3f(v3.x, v3.y, v3.z);

		glEnd();
	}

	glDisable(GL_TEXTURE_2D);
	glEndList();
	
	*success = true;
	return dlist;
}

void EntityManager::drawAll()
{
	vector<Entity*>::iterator it = entityList.begin();
	for (; it != entityList.end(); ++it)
	{
		Entity * ent = *it;
		if (ent == NULL) continue;
		ent->draw();
	}
}